import 'package:excel_utils/extend/string_extend.dart';
import 'package:excel_utils/pages/view/calendar_view.dart';
import 'package:excel_utils/pages/week/bean/DisCustomerRecordBean.dart';
import 'package:excel_utils/pages/week/week_entry/child/dis_customer_record/bloc/dis_customer_record_cubit.dart';
import 'package:excel_utils/pages/week/week_report/week_isolate/week_isloate.dart';
import 'package:excel_utils/repository/k8/k8_repository.dart';
import 'package:excel_utils/repository/week/dis_customer_record_repository.dart';
import 'package:excel_utils/widgets/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class DisCustomerRecordPage extends StatefulWidget {
  const DisCustomerRecordPage({super.key});

  @override
  State<DisCustomerRecordPage> createState() => _DisCustomerRecordPageState();
}

class _DisCustomerRecordPageState extends State<DisCustomerRecordPage> {
  DisCustomerRecordCubit? disCustomerRecordCubit;

  late DateTime? startDate;
  late DateTime? endDate;

  String disMonthFeeStartDate = "";
  String disMonthFeeEndDate = "";

  List<DisCustomerRecordBean> disCustomerRecordData = [];
  bool searchLoading = false;
  Set<String> deleteIdData = {};
  bool saveLoading = false;
  int year = 2025;
  int month = 09;
  int day = 04;

  dynamic monthlyFeeAll = 0;
  dynamic quantityKeDaAll = 0;
  dynamic sellingSilverCodeAll = 0;
  dynamic numberPackageTicketsAll = 0;
  dynamic sellingSilverCode_C_monthlyPackageTransferData = 0;
  Set<String> searchCustomerNo = {};

  @override
  void initState() {
    DateTime today = DateTime.now();
    // 判断今天是周几
    int currentWeekday = DateTime.now().weekday;
    // 如果是周三，则修改开始日期为周四
    int daysToSubtract = (currentWeekday - 3 + 7) % 7 + 7;
    DateTime lastWednesday = today.subtract(Duration(days: daysToSubtract));
    startDate = lastWednesday;
    startDate = DateTime(startDate!.year, startDate!.month, startDate!.day + 1, 00, 00, 00);
    //结束日期为今天
    endDate = today;
    endDate = DateTime(endDate!.year, endDate!.month, endDate!.day, 23, 59, 59);
    year = endDate!.year;
    month = endDate!.month;
    day = endDate!.day;

    print("startDate: $startDate");
    print("endDate: $endDate");

    disMonthFeeStartDate = "${startDate?.year}-${startDate?.month.toString().padLeft(2, '0')}-${startDate?.day.toString().padLeft(2, '0')}";
    disMonthFeeEndDate = "${endDate?.year}-${endDate?.month.toString().padLeft(2, '0')}-${endDate?.day.toString().padLeft(2, '0')}";

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<DisCustomerRecordCubit>(
      create: (_) => DisCustomerRecordCubit(context.read<DisCustomerRecordRepository>(), context.read<K8Repository>()),
      child: BlocConsumer<DisCustomerRecordCubit, DisCustomerRecordState>(
        builder: (BuildContext context, DisCustomerRecordState state) {
          disCustomerRecordCubit = disCustomerRecordCubit ?? context.read<DisCustomerRecordCubit>();

          if (state is DisCustomerRecordInitial) {
          } else if (state is DisCustomerRecordDataLoading) {
            searchLoading = true;
          } else if (state is DisCustomerRecordDataSuccessState) {
            searchLoading = false;
            disCustomerRecordData = state.disCustomerRecordData;
            try {
              monthlyFeeAll = disCustomerRecordData.fold(0.0, (value, element) => value + element.monthlyFee!);
              quantityKeDaAll = disCustomerRecordData.fold(0, (value, element) => value + element.quantityKeDa!);
            } catch (ex) {}
          } else if (state is DisCustomerRecordDataFailureState) {
            searchLoading = false;
          } else if (state is DisCustomerRecordDeleteLoading) {
            deleteIdData.add(state.disCustomerRecordId);
          } else if (state is DisCustomerRecordDeleteSuccessState) {
            deleteIdData.remove(state.disCustomerRecordId);
          } else if (state is DisCustomerRecordDeleteFailureState) {
            deleteIdData.remove(state.disCustomerRecordId);
          } else if (state is DisCustomerRecordSaveLoading) {
            saveLoading = true;
          } else if (state is DisCustomerRecordSaveSuccessState) {
            saveLoading = false;
            disCustomerRecordData = state.disCustomerRecordData;
          } else if (state is DisCustomerRecordSearchCustomerLoading) {
            searchCustomerNo.add(state.customerNo);
          } else if (state is DisCustomerRecordSearchCustomerSuccessState) {
            searchCustomerNo.remove(state.customerNo);
            // 查询数据，获取到对应的index
            for (var element in disCustomerRecordData) {
              if (element.customerNo == state.customerNo) {
                int index = disCustomerRecordData.indexOf(element);
                disCustomerRecordData[index].groupName = state.customerBean.data![0].bcName;

                String groupNameStr = disGetGroupName(state.customerBean.data![0].cmCode.toString(), state.customerBean.data![0].groupName.toString());
                disCustomerRecordData[index].groupName = groupNameStr;

                disCustomerRecordData[index].customerNo = state.customerBean.data![0].cmCode;
                disCustomerRecordData[index].customerName = state.customerBean.data![0].cmName;
                disCustomerRecordData[index].address = state.customerBean.data![0].cmAddress;

                disCustomerRecordData[index].monthlyFee = double.parse(state.customerBean.data![0].cmMonthcost.toString());
                disCustomerRecordData[index].quantityKeDa = state.customerBean.data![0].cmOrdernum;
              }
            }
          }

          return buildUI();
        },
        listener: (BuildContext context, DisCustomerRecordState state) {},
      ),
    );
  }

  Widget buildUI() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            " 停用客戶紀錄",
            style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.blue),
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              CalendarView(
                onInitDateChanged: (startDateTime, startStr, endDateTime, endStr) {
                  disMonthFeeStartDate = "${startStr}";
                  disMonthFeeEndDate = "${endStr}";
                },
                onDateStartChanged: (startDateTime, startStr) {
                  print("disMonthFeeStartDate: $startDateTime, $startStr");
                  disMonthFeeStartDate = "${startStr}";
                },
                onDateEndChanged: (endDateTime, endStr) {
                  print("disMonthFeeEndDate: $endDateTime, $endStr");
                  disMonthFeeEndDate = "${endStr}";
                },
              ),
              searchLoading
                  ? Center(child: CircularProgressIndicator())
                  : ElevatedButton(
                      child: Text("查询"),
                      onPressed: () {
                        disCustomerRecordCubit?.getDisCustomerRecord(maps: {
                          "startDate": disMonthFeeStartDate,
                          "endDate": disMonthFeeEndDate,
                        });
                      },
                    ),
            ],
          ),
          Table(
            children: [
              tabRows(["No", "收到日期", "群組", "直客/加盟商", "客戶號碼", "客戶名稱", "地址", "月費", "柯打數量", "终止日期", "停用原因", "日期范围", "操作"]),
              ...disCustomerRecordData.asMap().entries.map((element) {
                DisCustomerRecordBean e = element.value;
                return tabRowWidgets([
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: (element.key + 1).toString()),
                    readOnly: true,
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.noticeDate ?? ""),
                    onChanged: (value) => e.noticeDate = value.replaceAll("\r", ""),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.groupName ?? ""),
                    onChanged: (value) => e.groupName = value.replaceAll("\r", ""),
                  ),
                  Container(
                    child: DropdownMenu(
                      dropdownMenuEntries: const [
                        DropdownMenuEntry(value: 1, label: "CXC直客"),
                        DropdownMenuEntry(value: 2, label: "加盟商"),
                      ],
                      label: Text(e.directFranchisee == 1 ? "直客" : "加盟商"),
                      onSelected: (value) {
                        e.directFranchisee = value;
                        disCustomerRecordCubit?.refresh();
                      },
                    ),
                  ),
                  Container(
                    child: Stack(
                      children: [
                        TextField(
                          decoration: const InputDecoration(border: OutlineInputBorder()),
                          controller: TextEditingController(text: e.customerNo ?? ""),
                          onChanged: (value) => e.customerNo = value.replaceAll("\r", ""),
                        ),
                        Positioned(
                          right: 0,
                          top: 0,
                          child: IconButton(
                            icon: Icon(Icons.search),
                            onPressed: () {
                              disCustomerRecordCubit?.searchCustomer(customerNo: e.customerNo.toString().replaceAll("\r", ""));
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.customerName ?? ""),
                    onChanged: (value) => e.customerName = value.replaceAll("\r", ""),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.address ?? ""),
                    onChanged: (value) => e.address = value.replaceAll("\r", ""),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: "${e.monthlyFee}"),
                    onChanged: (value) {
                      try {
                        e.monthlyFee = double.parse(value.replaceAll("\r", ""));
                      } catch (ex) {
                        e.monthlyFee = 0.00;
                      }
                    },
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: "${e.quantityKeDa ?? 0}"),
                    onChanged: (value) {
                      try {
                        String valueStr = value.toString().replaceAll("\r", "").toString();
                        e.quantityKeDa = int.parse(valueStr);
                      } catch (ex) {
                        e.quantityKeDa = 0;
                      }
                    },
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: "${e.expDate}"),
                    onChanged: (value) => e.expDate = value.replaceAll("\r", ""),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.expReason.toString()),
                    onChanged: (value) => e.expReason = value.replaceAll("\r", ""),
                  ),
                  TextField(
                    decoration: const InputDecoration(border: OutlineInputBorder()),
                    controller: TextEditingController(text: e.dateRange.toString()),
                    onChanged: (value) => e.dateRange = value.replaceAll("\r", ""),
                  ),
                  TextButton(
                      onPressed: () {
                        if (e.id == null) {
                          disCustomerRecordData.removeAt(element.key);
                          disCustomerRecordCubit?.refresh();
                        } else {
                          disCustomerRecordCubit?.delDisCustomerRecord(disCustomerRecordId: e.id.toString());
                        }
                      },
                      child: Text("delete")),
                ]);
              }),
              tabRows([
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "${monthlyFeeAll}",
                "${quantityKeDaAll}",
                "",
                "",
                "",
                "",
              ]),
              tabRows([
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
                "",
              ]),
              tabRows([
                "日期",
                "月費總收入",
                "客戶數目",
                "加盟商 月費 總收入",
                "加盟商 客戶數目",
                "加盟商 百份比",
                "CXC直客 月費 總收入",
                "CXC直客 客戶 數目",
                "CXC直客 百份比",
                "",
                "",
                "",
                "",
              ]),
              tabRows([
                "${disMonthFeeStartDate.substring(5, 10)}-${disMonthFeeEndDate.substring(5, 10)}",
                "${monthlyFeeAll}",
                "${disCustomerRecordData.length}",
                "${disCustomerRecordData.fold(0.0, (value, element) {
                  // 加盟商
                  if (element.directFranchisee != 1) {
                    return value + element.monthlyFee!;
                  } else {
                    return value;
                  }
                })}",
                "${disCustomerRecordData.where((element) => element.directFranchisee != 1).length}",
                "${((disCustomerRecordData.fold(0.0, (value, element) {
                      // 加盟商
                      if (element.directFranchisee != 1) {
                        return value + element.monthlyFee!;
                      } else {
                        return value;
                      }
                    }) / monthlyFeeAll * 100).toStringAsFixed(1))}%",
                "${disCustomerRecordData.fold(0.0, (value, element) {
                  // 加盟商
                  if (element.directFranchisee == 1) {
                    return value + element.monthlyFee!;
                  } else {
                    return value;
                  }
                })}",
                "${disCustomerRecordData.where((element) => element.directFranchisee == 1).length}",
                "${((disCustomerRecordData.fold(0.0, (value, element) {
                      // 加盟商
                      if (element.directFranchisee == 1) {
                        return value + element.monthlyFee!;
                      } else {
                        return value;
                      }
                    }) / monthlyFeeAll * 100).toStringAsFixed(1))}%", // / 总额，转为百分比，保留1小数
                "",
                "",
                "",
                "",
              ]),
            ],
          ),
          SizedBox(height: 10),
          Row(
            children: [
              SizedBox(width: 10),
              ElevatedButton(
                  onPressed: () {
                    StringBuffer sb = StringBuffer();
                    for (int index = 0; index < disCustomerRecordData.length; index++) {
                      DisCustomerRecordBean monthlyPackageTransfer = disCustomerRecordData[index];
                      String tempStr = "";
                      tempStr += "${index + 1}\t";
                      tempStr += "${monthlyPackageTransfer.noticeDate ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.groupName ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.customerNo ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.customerName ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.address ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.monthlyFee ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.quantityKeDa ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.expDate ?? ""}\t";
                      tempStr += "${monthlyPackageTransfer.expReason ?? ""}\t";
                      sb.writeln(tempStr);
                    }
                    String summary = "";
                    summary += "\t\t\t\t\t\t";
                    summary += "${monthlyFeeAll}\t${quantityKeDaAll}\t";
                    summary += "\t\t\t\t\t\t";
                    sb.writeln(summary);
                    sb.toString().copyValue();
                  },
                  child: Text("COPY")),
              ElevatedButton(
                  onPressed: () {
                    StringBuffer sb = StringBuffer();

                    sb.write("${disMonthFeeStartDate.substring(5, 10)}-${disMonthFeeEndDate.substring(5, 10)}\t");
                    sb.write("${monthlyFeeAll}\t");
                    sb.write("${disCustomerRecordData.length}\t");
                    sb.write("${disCustomerRecordData.fold(0.0, (value, element) {
                      // 加盟商
                      if (element.directFranchisee != 1) {
                        return value + element.monthlyFee!;
                      } else {
                        return value;
                      }
                    })}\t");
                    sb.write("${disCustomerRecordData.where((element) => element.directFranchisee != 1).length}\t");
                    sb.write("${((disCustomerRecordData.fold(0.0, (value, element) {
                          // 加盟商
                          if (element.directFranchisee != 1) {
                            return value + element.monthlyFee!;
                          } else {
                            return value;
                          }
                        }) / monthlyFeeAll * 100).toStringAsFixed(1))}%\t");
                    sb.write(
                      "${disCustomerRecordData.fold(0.0, (value, element) {
                        // 加盟商
                        if (element.directFranchisee == 1) {
                          return value + element.monthlyFee!;
                        } else {
                          return value;
                        }
                      })}\t",
                    );
                    sb.write("${disCustomerRecordData.where((element) => element.directFranchisee == 1).length}\t");
                    sb.write("${((disCustomerRecordData.fold(0.0, (value, element) {
                          // 加盟商
                          if (element.directFranchisee == 1) {
                            return value + element.monthlyFee!;
                          } else {
                            return value;
                          }
                        }) / monthlyFeeAll * 100).toStringAsFixed(1))}%\t"); // / 总额，转为百分比，保留1小数
                    sb.toString().copyValue();
                  },
                  child: Text("汇总数据")),
              SizedBox(width: 10),
              ElevatedButton(
                  onPressed: () {
                    DateTime now = DateTime.now();
                    String createDate = "${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}";
                    disCustomerRecordData.add(DisCustomerRecordBean(
                        noticeDate: "",
                        groupName: "",
                        customerNo: "",
                        customerName: "",
                        address: "",
                        monthlyFee: 0.00,
                        quantityKeDa: 0,
                        dateRange: "",
                        createDate: "${createDate}"));
                    setState(() {});
                  },
                  child: Text("添加")),
              SizedBox(width: 10),
              saveLoading
                  ? CircularProgressIndicator()
                  : ElevatedButton(
                      onPressed: () {
                        bool isNotEmpty = false;
                        for (var monthlyPackageTransfer in disCustomerRecordData) {
                          if (monthlyPackageTransfer.noticeDate == "") {
                            isNotEmpty = true;
                            break;
                          }
                          if (monthlyPackageTransfer.groupName == "") monthlyPackageTransfer.groupName = " ";
                          if (monthlyPackageTransfer.customerName == "") monthlyPackageTransfer.customerName = " ";
                          if (monthlyPackageTransfer.address == "") monthlyPackageTransfer.address = " ";
                          monthlyPackageTransfer.monthlyFee ??= 0.00;
                          monthlyPackageTransfer.quantityKeDa ??= 0;
                          if (monthlyPackageTransfer.expDate == "") monthlyPackageTransfer.expDate = " ";
                          if (monthlyPackageTransfer.expReason == "") monthlyPackageTransfer.expReason = " ";
                          if (monthlyPackageTransfer.dateRange == "") {
                            isNotEmpty = true;
                            break;
                          }
                        }
                        if (isNotEmpty) {
                          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("请填写完整数据")));
                          return;
                        }
                        disCustomerRecordCubit?.saveDisCustomerRecord(disCustomerRecordData: disCustomerRecordData);
                      },
                      child: Text("保存")),
            ],
          ),
          SizedBox(height: 10),
        ],
      ),
    );
  }
}
